"use client";

import { Calculator, Calendar, CreditCard, Search, Settings, Smile, User } from "lucide-react";
import * as React from "react";

import {
  CommandDialog,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
  CommandSeparator,
  CommandShortcut,
} from "@/components/ui/command";

import { Button } from "./ui/button";
import { ScrollArea } from "./ui/scroll-area";

export function GlobalSearch() {
  const [open, setOpen] = React.useState(false);
  const [keyword, setKeyword] = React.useState("");

  React.useEffect(() => {
    const down = (e: KeyboardEvent) => {
      if (e.key === "k" && (e.metaKey || e.ctrlKey)) {
        e.preventDefault();
        setOpen((open) => !open);
      }
    };

    document.addEventListener("keydown", down);
    return () => document.removeEventListener("keydown", down);
  }, []);

  return (
    <>
      <Button
        size={"sm"}
        className="relative h-8 w-full justify-start gap-2 bg-muted/70 px-2 text-muted-foreground"
        variant={"secondary"}
        onClick={() => setOpen(true)}
      >
        <Search />
        <span className="truncate">搜索...</span>
        <kbd className="pointer-events-none ml-auto hidden h-5 select-none items-center gap-1 rounded border bg-muted px-1.5 font-mono text-[10px] font-medium opacity-100 sm:flex">
          <span className="text-xs">⌘</span>K
        </kbd>
      </Button>
      <CommandDialog open={open} onOpenChange={setOpen}>
        <CommandInput placeholder="搜索你想要的工具" value={keyword} onValueChange={setKeyword} />
        <CommandList>
          <ScrollArea className="h-[300px]">
            <CommandEmpty>搜索不到{`"${keyword}"`}相关的工具</CommandEmpty>
            <CommandGroup heading="常用工具">
              <CommandItem>
                <Calendar />
                <span>日历</span>
              </CommandItem>
              <CommandItem>
                <Smile />
                <span>搜索 Emoji</span>
              </CommandItem>
              <CommandItem>
                <Calculator />
                <span>计算器</span>
              </CommandItem>
            </CommandGroup>
            <CommandSeparator />
            <CommandGroup heading="我的收藏">
              <CommandItem>
                <User />
                <span>Json格式化</span>
                <CommandShortcut>⌘P</CommandShortcut>
              </CommandItem>
              <CommandItem>
                <CreditCard />
                <span>记账</span>
                <CommandShortcut>⌘B</CommandShortcut>
              </CommandItem>
              <CommandItem>
                <Settings />
                <span>不知道</span>
                <CommandShortcut>⌘S</CommandShortcut>
              </CommandItem>
            </CommandGroup>
          </ScrollArea>
        </CommandList>
      </CommandDialog>
    </>
  );
}
